package com.my.note.conf;

import com.my.note.security.Md5PasswordEncoder;
import com.my.note.security.NoteAccessDecisionManagerImpl;
import com.my.note.security.NoteAccessDeniedHandler;
import com.my.note.security.NoteFilterInvocationSecurityMetadataSourceImpl;
import com.my.note.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
 * @author lilun <a href="mailto:lil@chsi.com.cn">lilun</a>
 * @version $Id$ 2019年03月20 11:47
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    NoteFilterInvocationSecurityMetadataSourceImpl noteFilterInvocationSecurityMetadataSource;

    @Autowired
    NoteAccessDecisionManagerImpl noteAccessDecisionManager;

    @Autowired
    NoteAccessDeniedHandler noteAccessDeniedHandler;

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new Md5PasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/", "/index");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
                withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(noteFilterInvocationSecurityMetadataSource);
                        o.setAccessDecisionManager(noteAccessDecisionManager);
                        return o;
                    }
                }).and().formLogin().loginProcessingUrl("/login").permitAll().and().csrf().disable();

    }
}
